package com.android.love.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.widget.ProgressBar;

public class DownLoadUtil {

	/**
	 * 下载一个文件
	 * 
	 * @param urlpath
	 *            下载路径
	 * @param filePath
	 *            保存路径
	 * @param pb
	 *            进度条对话框
	 */

	public static File getFile(String urlpath, String filePath, ProgressBar pb) {
		try {
			URL url = new URL(urlpath);
			File file = new File(filePath);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			int code = conn.getResponseCode();
			if (code == 200) {
				InputStream in = conn.getInputStream();
				OutputStream out = new FileOutputStream(file);
				pb.setMax(conn.getContentLength());
				byte[] buffer = new byte[1024];
				int len = 0;
				int process = 0;
				while ((len = in.read(buffer)) != -1) {
					out.write(buffer, 0, len);
					process += len;
					pb.setProgress(process);
				}
				out.close();
				in.close();
				return file;
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

}
